# coding=utf-8
__author__ = 'st316'
'''
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
注意： 处理溢出位，注意顺序反向
'''


#Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def toString(self):
        cur = self
        s = ''
        while cur.next:
            s += str(cur.val) + ' -> '
            cur = cur.next
        return s + str(cur.val)


class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
        cur1 = l1
        cur2 = l2
        next1 = cur1.next
        next2 = cur2.next
        c = 0
        c, r = self.addDigit(cur1.val, cur2.val, c)
        res = ListNode(r)
        head = res
        while next1 and next2:
            c, r = self.addDigit(next1.val, next2.val, c)
            post = ListNode(r)
            res.next = post
            res = post
            next1 = next1.next
            next2 = next2.next
        if next1 and not next2:  # l2已经走完
            while next1:
                c, r = self.addDigit(next1.val, 0, c)
                post = ListNode(r)
                res.next = post
                res = post
                next1 = next1.next
        elif not next1 and next2:  # l1已经走完
            while next2:
                c, r = self.addDigit(0, next2.val, c)
                post = ListNode(r)
                res.next = post
                res = post
                next2 = next2.next
        if c != 0:  # 处理溢出位
            post = ListNode(c)
            res.next = post
        return head

    def addDigit(self, a, b, c):
        return (a + b + c) / 10, (a + b + c) % 10


if __name__ == '__main__':
    l1 = ListNode(1)
    l1.next = ListNode(8)
    l2 = ListNode(0)
    s = Solution()
    print s.addTwoNumbers(l1, l2).toString()